package homework1.utils;

import homework1.common.Message;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.io.*;
import java.util.Base64;

/**
 * 工具类
 *
 * @author jian
 * @date 2024/01/09 10:40
 **/
public class Tool {

    private static final String AES_KEY = "ItIsSecretKey123";

    public static boolean fileIsExist(String filePath){
        // 创建File对象
        File file = new File(filePath);

        // 使用 exists() 方法判断文件是否存在
        if (file.exists()) {
            return true;
        } else {
            return false;
        }
    }
    public static void saveToFile(byte[] data, String filePath) throws IOException {
        try (FileOutputStream fos = new FileOutputStream(filePath)) {
            fos.write(data);
        }
    }

    public static void checkFile(String filePath) {
        BufferedReader fileReader = null;
        try {
            fileReader = new BufferedReader(new FileReader(filePath));
            String line;
            while ((line = fileReader.readLine()) != null) {
                System.out.println(line);
            }
        }
        catch (IOException e) {
            System.out.println("查看文件内容异常：");
            throw new RuntimeException(e);
        }
    }
    public static void sendEncryptedFile(ObjectOutputStream oos, String filePath) throws Exception{
        Message message = new Message();
        if (filePath.endsWith("xml")){
            message.setContentType("xml");
        }
        else if (filePath.endsWith("json")){
            message.setContentType("json");
        }
        File file = new File(filePath);
        try (FileInputStream fileInputStream = new FileInputStream(file)) {
            byte[] fileData = new byte[(int) file.length()];
            fileInputStream.read(fileData);

            // 加密文件数据
            byte[] encryptedData = encryptFile(fileData);

            message.setFileBytes(encryptedData);

            // 发送 FileInfo 对象
            oos.writeObject(message);
        }
    }
    public static byte[] decryptFileContent(byte[] encryptedFileContent) throws Exception {
        byte[] keyBytes = AES_KEY.getBytes();
        SecretKey secretKey = new SecretKeySpec(keyBytes, "AES");

        Cipher cipher = Cipher.getInstance("AES");
        cipher.init(Cipher.DECRYPT_MODE, secretKey);

        return cipher.doFinal(Base64.getDecoder().decode(encryptedFileContent));
    }

    private static byte[] encryptFile(byte[] fileData) throws Exception {
        byte[] keyBytes = AES_KEY.getBytes();
        SecretKey secretKey = new SecretKeySpec(keyBytes, "AES");

        Cipher cipher = Cipher.getInstance("AES");
        cipher.init(Cipher.ENCRYPT_MODE, secretKey);

        byte[] encryptedBytes = cipher.doFinal(fileData);
        return Base64.getEncoder().encode(encryptedBytes);
    }


    //获取socket输入流，并将文件解密保存



}